<template>
    <div class="viewer">
        <vc-viewer :animation="animation" :timeline="timeline" :camera.sync="camera" @ready="ready"
            @LEFT_CLICK="onMapClick">
            <!-- <vc-layer-imagery>
                <vc-provider-imagery-ion :asset-id="4" :access-token="accessToken"></vc-provider-imagery-ion>
            </vc-layer-imagery> -->
            <!-- <vc-layer-imagery ref="layerText" :alpha="1" :brightness="1" :contrast="1" :sort-order="20">
                <vc-provider-imagery-tianditu map-style="'ter_c" :token="tiandituToken"></vc-provider-imagery-tianditu>
            </vc-layer-imagery>
            <vc-layer-imagery :alpha="1" :brightness="1" :contrast="1" :sort-order="10">
                <vc-provider-imagery-tianditu map-style="ter_c" :token="tiandituToken"></vc-provider-imagery-tianditu>
            </vc-layer-imagery> -->


            <vc-layer-imagery :alpha="alpha" :brightness="brightness" :contrast="contrast" :sort-order="10">
                <vc-provider-imagery-amap :map-style="mapStyle" :ltype="ltype"
                    :projection-transforms="projectionTransforms"></vc-provider-imagery-amap>
            </vc-layer-imagery>
            <vc-layer-imagery :sort-order="5">
                <vc-provider-imagery-tianditu map-style="img_w" :token="tiandituToken"></vc-provider-imagery-tianditu>
            </vc-layer-imagery>


            <vc-provider-terrain-cesium></vc-provider-terrain-cesium>
            <vc-analytics-flood ref="flood" :min-height="minHeight" :max-height="maxHeight" :speed="speed"
                :polygon-hierarchy="polygonHierarchy" @stop="onStoped"></vc-analytics-flood>
        </vc-viewer>

        <!-- 悬浮框 -->
        <div class="control-panel">
            <div class="control-item">
                <label for="minHeight">最小高度</label>
                <el-input-number id="minHeight" v-model="minHeight" :min="-1" :max="10000"
                    style="margin-left: 10px;"></el-input-number>
            </div>
            <div class="control-item">
                <label for="maxHeight">最大高度</label>
                <el-input-number id="maxHeight" v-model="maxHeight" :min="10" :max="1000000"
                    style="margin-left: 10px;"></el-input-number>
            </div>
            <div class="control-item">
                <label for="speed">速度</label>
                <el-slider id="speed" v-model="speed" :min="1" :max="100" :step="1"
                    style="margin-left: 10px; width: calc(100% - 60px);"></el-slider>
            </div>
            <div class="control-item">
                <label for="radius">分析范围 (公里)</label>
                <el-input-number id="radius" v-model="radius" @change="setFloodArea" :min="1" :max="1000"
                    style="margin-left: 10px;"></el-input-number>
            </div>
            <div class="control-item">
                <el-button type="primary" @click="start">开始</el-button>
                <el-button type="info" @click="pause">暂停</el-button>
                <el-button type="danger" @click="stop">结束</el-button>
            </div>
            <div class="control-item">
                <el-button type="success" @click="startRechooce">开始重选</el-button>
                <el-button type="danger" @click="stopRechooce">结束重选</el-button>
            </div>

            <div style="position: absolute; top: 325px; left: 0px; z-index: 9999; width: 525px;" class="input-card"
            v-show="showChart">
             <!-- 关闭按钮 -->
                <el-button type="danger" icon="el-icon-close" circle @click="showChart = false" style="position: absolute;z-index: 10000; top: 10px; left: 10px;"></el-button>
<!-- 
                <el-row :gutter="5">
                        <el-col :span="8">
                            <el-select v-model="selectedTimeType" placeholder="请选择时间类型" @change="handleTimeTypeChange">
                                <el-option label="小时" value="hour"></el-option>
                                <el-option label="天" value="day"></el-option>
                                <el-option label="月" value="month"></el-option>
                                <el-option label="年" value="year"></el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="16">
                            <el-date-picker v-model="selectedTimeRange" :type="timePickerType" start-placeholder="开始时间"
                                end-placeholder="结束时间" range-separator="-" value-format="yyyy-MM-dd HH:mm:ss"
                                :picker-options="pickerOptions" @change="getChartData"></el-date-picker>
                        </el-col>
                    </el-row> -->
                    <custom-chart :data="chartData" :fields="['temperature', 'humidity', 'water', 'rain']"
                        :time-type="selectedTimeType" width="100%" height="325px" />

        </div>
        </div>
    </div>
</template>

<script>
import { getAll } from "@/api/system/station";
import { searchData } from "@/api/system/data";
import CustomChart from './CustomChart.vue';
export default {
    components: {
        CustomChart
    },
    data() {
        return {
            timePickerType: 'datetimerange',
            animation: true,
            timeline: true,
            camera: {
                position: {
                    lon: 103.34217370088817,
                    lat: 30.697503663421976,
                    height: 100000,
                },
                heading: 360,
                pitch: -90,
                roll: 0,
            },
            accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwZDRkMDRhOS02ZjNiLTRhZTItYjM1ZS01MDQ3ZTIxYTIyYjYiLCJpZCI6Mjg2NDUzLCJpYXQiOjE3NDI1NjI5ODF9.tV-SqBVOeF1DOdxmkALanCBYXneRBHQoxkFhD1Fl0vw',
            tiandituToken: '269f4c6f4515f49b49674ab3d489a105',
            minHeight: -1,
            maxHeight: 1000,
            speed: 10,
            radius: 10, // 默认分析范围为 10 公里
            polygonHierarchy: [],
            pausing: false,
            starting: false,
            initialPointEntit: null,
            initPointPosition: {
                lon: 103.34217370088817,
                lat: 30.697503663421976,
                height: 100
            },
            viewer: null,
            cesium: null,
            rechoose: false,

            alpha: 1,
            brightness: 1,
            contrast: 1,
            mapStyle: '6',
            ltype: '0',
            projectionTransforms: {
                form: 'BD09',
                to: 'WGS84'
            },
            stations:[],
            showChart:false,
            selectedTimeType: 'hour',
            selectedTimeRange: [],
            pickerOptions: {
                disabledDate(time) {
                    return false; // 默认不禁用任何日期
                }
            },
            chartData: [],
            selectedStation: null,
            searchDataParam: {
                stationId: null,
                timeType: null,
                params: {
                    beginTime: null,
                    endTime: null
                }
            },
        };
    },
    methods: {
        ready(cesiumInstance) {

            const { Cesium, viewer } = cesiumInstance;
            this.viewer = viewer;
            this.cesium = Cesium;
            this.initialPointEntity = viewer.entities.add(this.getInitPoint(this.initPointPosition.lon, this.initPointPosition.lat, this.initPointPosition.height));
            // 设置相机位置
            viewer.camera.setView({
                destination: Cesium.Cartesian3.fromDegrees(this.initPointPosition.lon, this.initPointPosition.lat, 10000),
                orientation: {
                    heading: Cesium.Math.toRadians(0),
                    pitch: Cesium.Math.toRadians(-45),
                    roll: 0.0,
                },
            });

            // 缩放变小（摄像头离目标点更远）
            viewer.camera.zoomOut(90000);
            this.setFloodArea();
            this.getStaions();
        },
        handleTimeTypeChange(value) {
            this.selectedTimeType = value;
            switch (value) {
                case 'hour':
                    this.timePickerType = 'datetimerange';
                    this.pickerOptions = {
                        disabledDate(time) {
                            return false; // 默认不禁用任何日期
                        }
                    };
                    break;
                case 'day':
                    this.timePickerType = 'daterange';
                    this.pickerOptions = {
                        disabledDate(time) {
                            return false; // 默认不禁用任何日期
                        }
                    };
                    break;
                case 'month':
                    this.timePickerType = 'monthrange';
                    this.pickerOptions = {
                        disabledDate(time) {
                            return false; // 默认不禁用任何日期
                        }
                    };
                    break;
                case 'year':
                    this.timePickerType = 'daterange';
                    this.pickerOptions = {
                        disabledDate(time) {
                            return false; // 默认不禁用任何日期
                        },
                        firstDayOfWeek: 1, // 设置每周的第一天为周一
                        shortcuts: [
                            {
                                text: '今年',
                                onClick(picker) {
                                    const start = new Date();
                                    start.setFullYear(start.getFullYear());
                                    start.setMonth(0);
                                    start.setDate(1);
                                    const end = new Date();
                                    end.setFullYear(end.getFullYear() + 1);
                                    end.setMonth(0);
                                    end.setDate(0);
                                    picker.$emit('pick', [start, end]);
                                }
                            },
                            {
                                text: '去年',
                                onClick(picker) {
                                    const start = new Date();
                                    start.setFullYear(start.getFullYear() - 1);
                                    start.setMonth(0);
                                    start.setDate(1);
                                    const end = new Date();
                                    end.setFullYear(end.getFullYear());
                                    end.setMonth(0);
                                    end.setDate(0);
                                    picker.$emit('pick', [start, end]);
                                }
                            }
                        ]
                    };
                    break;
                default:
                    this.timePickerType = 'datetimerange';
                    this.pickerOptions = {
                        disabledDate(time) {
                            return false; // 默认不禁用任何日期
                        }
                    };
            }
            this.getChartData();
        },
        setDefaultTimeRange() {
            const now = new Date();
            const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0); // 今天零点
            const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), 0, 0); // 现在所在的小时

            // 格式化为 yyyy-MM-dd HH:mm:ss
            const formatTime = (date) => {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            };

            this.selectedTimeRange = [formatTime(start), formatTime(end)];
        },
        getChartData() {
            this.searchDataParam.stationId = this.selectedStation;
            this.searchDataParam.timeType = this.selectedTimeType;
            if (null != this.selectedTimeRange && '' != this.selectedTimeRange) {
                this.searchDataParam.params["beginTime"] = this.selectedTimeRange[0];
                this.searchDataParam.params["endTime"] = this.selectedTimeRange[1];
            }

            searchData(this.searchDataParam).then((res) => {
                this.chartData = res.data;
            })
        },
        getStaions() {
            getAll().then((res) => {
                this.stations = res.data;
                this.showAllStation();
            })
        },
        showAllStation() {
            var stataions = this.stations
            for (var i = 0; i < stataions.length; i++) {
                var point = this.getPoint(stataions[i]);
                this.viewer.entities.add(point);
            }
             // 设置点击事件
            this.viewer.screenSpaceEventHandler.setInputAction((movement) => {
                const pickedEntity = this.viewer.scene.pick(movement.position);
                this.viewer.selectedEntity = pickedEntity.id;
                console.log(pickedEntity.id.stationId)
                // 设置默认值
                if (pickedEntity.id&&pickedEntity.id.stationId) {
                    this.selectedStation = pickedEntity.id.stationId; // 默认选择站点
                    this.selectedTimeType = 'hour'; // 默认选择小时
                    this.setDefaultTimeRange(); // 设置默认时间范围   
                    this.getChartData();//获取图表数据
                    this.showChart = true;
                }
                
            }, this.cesium.ScreenSpaceEventType.LEFT_CLICK);
        },
        getPoint(station) {
            return {
                stationId:station.stationId,
                id: station.stationName,
                position: this.cesium.Cartesian3.fromDegrees(station.lon, station.lat, station.altitude),
                point: {
                    pixelSize: 5,
                    color: this.cesium.Color.RED,
                },
                label: {
                    text: station.stationName, // 显示的文本内容
                    font: '16px monospace', // 字体样式
                },
                // 自定义属性，用于点击时显示更多信息
                description: `站点名称：${station.stationName}<br>地址：${station.address}<br>经度：${station.lon}<br>纬度：${station.lat}<br>海拔：${station.altitude}<br监测时间：${station.monitorTime}`
            }
        },
        start() {
            this.$refs.flood.start();
            this.pausing = false;
        },
        pause() {
            this.$refs.flood.pause();
            this.pausing = !this.pausing;
        },
        stop() {
            this.$refs.flood.stop();
            this.pausing = false;
            this.starting = false;
        },
        onStoped(e) {
            this.pausing = false;
            this.starting = false;
            console.log(e);
        },
        onMapClick(event) {
            if (this.rechoose) {
                const cartesian = this.viewer.scene.pickPosition(event.position);
                if (cartesian) {
                    const cartographic = this.cesium.Cartographic.fromCartesian(cartesian);
                    const longitude = this.cesium.Math.toDegrees(cartographic.longitude);
                    const latitude = this.cesium.Math.toDegrees(cartographic.latitude);

                    // 获取地形高度
                    const terrainHeight = this.viewer.scene.globe.getHeight(cartesian);
                    const height = terrainHeight ? terrainHeight : 0;

                    console.log(`经度：${longitude}, 纬度：${latitude}, 高度：${height}`);

                    if (this.initialPointEntity && this.viewer) {
                        // 删除实体
                        this.viewer.entities.remove(this.initialPointEntity);
                        this.initialPointEntity = null; // 清除引用
                        this.initPointPosition.lon = longitude;
                        this.initPointPosition.lat = latitude;
                        this.initPointPosition.height = height;

                        this.initialPointEntity = this.viewer.entities.add(this.getInitPoint(longitude, latitude, height));

                        this.setFloodArea();
                    }
                }
            }
        },
        startRechooce() {
            this.rechoose = true;
            // 设置相机位置
            this.viewer.camera.setView({
                destination: Cesium.Cartesian3.fromDegrees(this.initPointPosition.lon, this.initPointPosition.lat, 10000),
                orientation: {
                    heading: Cesium.Math.toRadians(0),
                    pitch: Cesium.Math.toRadians(-90),
                    roll: 0.0,
                },
            });

        },
        stopRechooce() {
            this.rechoose = false;
            // 设置相机位置
            this.viewer.camera.setView({
                destination: Cesium.Cartesian3.fromDegrees(this.initPointPosition.lon, this.initPointPosition.lat, 10000),
                orientation: {
                    heading: Cesium.Math.toRadians(0),
                    pitch: Cesium.Math.toRadians(-45),
                    roll: 0.0,
                },
            });

            // 缩放变小（摄像头离目标点更远）
            this.viewer.camera.zoomOut(90000);
        },
        getInitPoint(lon, lat, height) {
            return {
                id: '初始节点',
                position: this.cesium.Cartesian3.fromDegrees(lon, lat, height),
                point: {
                    pixelSize: 10,
                    color: this.cesium.Color.RED,
                },
            }
        },
        setFloodArea() {
            if (this.initialPointEntity) {
                const centerLongitude = this.initPointPosition.lon; // 中心点经度
                const centerLatitude = this.initPointPosition.lat; // 中心点纬度
                const radiusInKm = this.radius; // 半径（公里）
                const radiusInMeters = radiusInKm * 1000; // 半径（米）

                // 计算纬度偏移量（以度为单位）
                const latitudeOffset = radiusInMeters / 110574;

                // 计算经度偏移量（以度为单位）
                const longitudeOffset = radiusInMeters / (111320 * Math.cos(centerLatitude * Math.PI / 180));

                // 计算四个顶点的经纬度
                const positions = [
                    centerLongitude - longitudeOffset, centerLatitude - latitudeOffset, // 左下角
                    centerLongitude + longitudeOffset, centerLatitude - latitudeOffset, // 右下角
                    centerLongitude + longitudeOffset, centerLatitude + latitudeOffset, // 右上角
                    centerLongitude - longitudeOffset, centerLatitude + latitudeOffset  // 左上角
                ];

                // 更新 polygonHierarchy
                this.polygonHierarchy = [
                    { lng: positions[0], lat: positions[1] },
                    { lng: positions[2], lat: positions[3] },
                    { lng: positions[4], lat: positions[5] },
                    { lng: positions[6], lat: positions[7] }
                ];
                console.log(this.polygonHierarchy)
            }
        }
    },
};
</script>

<style>
.viewer {
    width: 100%;
    height: 800px;
    position: relative;
}
.input-card {
    background-color: white;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
}


.control-panel {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 1000;
    background-color: rgba(0, 0, 0, 0.5);
    padding: 10px;
    border-radius: 5px;
    width: 300px;
    color: white;
}

.control-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.control-item label {
    margin-right: 10px;
    font-weight: bold;
}

.control-item .el-slider {
    flex: 1;
}
</style>